#include "head.h"

// int len;
// recv(socket_fd, &len, sizeof(int), 0);
// char path[60] = { 0 };
// recv(socket_fd, path, len, 0);                          
// char *ret = cd(path);

#if 0
//1.0
//cd函数
//返回值：0:成功 -1:失败
//参数：net_fd文件标识符，filename:想去的文件夹名
int cd(int net_fd, char *filename){
    //获取当前目录
    char path[100];
    bzero(path,sizeof(path));
    getcwd(path,sizeof(path));
    //拼接绝对路径
    strcat(path,filename);
    int len=strlen(path);
    path[len]='\0';

    //判断是否存在该目录
    printf("%s\n",path);
    int ret = access(path,F_OK);
    if(ret==0){
        int flag=0;
        send(net_fd,&flag , sizeof(int), 0);
        return -1;

    }
    int flag=1;
    send(net_fd, &flag, sizeof(int), 0);
    return 0;


}
#if 0
DIR * dir = opendir(path);
ERROR_CHECK(dir, NULL, "opendir");

//用dirent判断当前目录中fiename是否存在
struct dirent *namelist;
memset(&namelist, 0, sizeof(namelist));

while( (namelist = readdir(dir)) != NULL ){
    //判断
    if(strcmp(namelist->d_name, filename) == 0){
        break;
    }
}

if(namelist == NULL){
    printf("输入的目录不存在\n");
    //返回当前目录
    closedir(dir);
    //向客户端发送失败的消息
    send(net_fd, "-1", 1, 0);
    return -1;
}

closedir(dir);

//向客户端发送成功消息
send(net_fd, "0", 1, 0);
return 0;
}


// 单元测试函数
void test_cd() {
    char *test_cases[] = {"testdir", "notestdir"};
    int num_cases = sizeof(test_cases) / sizeof(test_cases[0]);

    for (int i = 0; i < num_cases; i++) {
        int result = cd(test_cases[i]);
        if (result == 0) {
            printf("Test case '%s': Passed\n", test_cases[i]);
        } else {
            printf("Test case '%s': Failed\n", test_cases[i]);
        }
    }
}

int main() {
    // 运行单元测试
    test_cd();
    return 0;
}
#endif
#endif

//服务端 2.0
//cd函数
//返回值：0:成功 -1:失败
//参数：net_fd文件标识符，msg结构体
int cd(int net_fd, transport_protocol_t *msg){
    MYSQL_RES *res;
    MYSQL_ROW row;

    char name[100] = { 0 };
    recv(net_fd, name, sizeof(name), 0);
   

    char sql_query[1000] = { 0 };
    strcat(sql_query,"select url from bd_file where url =  ");
    strcat(sql_query, "'");
    strcat(sql_query, name);
    strcat(sql_query, "'");
    strcat(sql_query, " and delete_flag = 0  and file_type = 1 and user_id =  ");
    strcat(sql_query,  msg->user_id);
    // 执行查询
    if (mysql_query(&msg->my_sql, sql_query)) {
        //printf("%s\n", mysql_error(&msg->my_sql));
        LOG_WRITE(3, "error:sql write error");
        return 1;
    }

    // 获取查询结果
    res = mysql_store_result(&msg->my_sql);

    // 遍历查询结果
    while ((row = mysql_fetch_row(res))) {
        if (strcmp(row[0], name) == 0){
            // 向客户端发送成功信息
            int flag = 0;
            send(net_fd, &flag, sizeof(int), 0);
            return 0;
        }
    }

    int flag = -1;
    send(net_fd, &flag, sizeof(int), 0);

    mysql_free_result(res);
    return -1;
}

